package com.android.toast

import android.app.Activity
import android.app.Application
import android.os.Build
import android.os.Bundle

/**
 * @Author LuoKun
 * @Des
 */
class ActivityLifecycle : Application.ActivityLifecycleCallbacks {

    private var mActivity: Activity? = null
    private var androidToast: AndroidToast<*>? = null

    constructor(mActivity: Activity, androidToast: AndroidToast<*>) {
        this.mActivity = mActivity
        this.androidToast = androidToast
    }

    /**注册监听*/
    fun register() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            mActivity?.registerActivityLifecycleCallbacks(this)
        } else {
            mActivity?.application?.registerActivityLifecycleCallbacks(this)
        }
    }

    /**取消监听*/
    fun unregister() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            mActivity?.unregisterActivityLifecycleCallbacks(this)
        } else {
            mActivity?.application?.unregisterActivityLifecycleCallbacks(this)
        }
    }

    override fun onActivityCreated(p0: Activity, p1: Bundle?) {

    }

    override fun onActivityStarted(p0: Activity) {

    }

    override fun onActivityResumed(p0: Activity) {

    }

    override fun onActivityPaused(p0: Activity) {
        /**需要在这里销毁 放在onDestroyed方法中还是有几率内存泄露*/
        if (mActivity != p0 || !mActivity!!.isFinishing || androidToast == null || !androidToast!!.isShowing()) {
            return
        }
        androidToast?.cancel()
    }

    override fun onActivityStopped(p0: Activity) {

    }

    override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
    }

    override fun onActivityDestroyed(p0: Activity) {
        if(mActivity != p0){
            return
        }
        mActivity = null
        if(androidToast == null){
            return
        }
        androidToast?.recycle()
        androidToast = null
    }
}